<template>
  <div class="opportunity-list text-yxt-grey-900 text-sm px-6">
    <el-table
      :data="list"
      v-loading="loading"
      style="width: 100%"
      :header-cell-style="{
        backgroundColor: '#fafafa',
        color: '#606266',
        fontWeight: '500',
      }"
      :row-style="{ height: '60px' }"
      element-loading-text="加载中..."
    >
      <el-table-column prop="name" label="商机名称" width="200">
        <template #default="{ row }">
          <div class="opportunity-name">{{ row.name || row.opportunityName }}</div>
        </template>
      </el-table-column>

      <el-table-column label="商机状态" width="120">
        <template #default="{ row }">
          <div class="flex items-center gap-1">
            <div
              class="w-[6px] h-[6px] rounded-full"
              :style="{
                backgroundColor: getStatusInfo(row.status).color,
              }"
            ></div>
            <p>{{ getStatusInfo(row.status).name }}</p>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="MEDDIC" width="220">
        <template #default="{ row }">
          <MeddicIndicator :meddicInfo="row.meddicList" />
        </template>
        <template #header>
          <div class="flex justify-between items-center">
            <p>MEDDIC</p>
            <el-tooltip effect="light" popper-class="meddic-tooltip">
              <template #content>
                <div class="p-2 w-[300px]">
                  <div
                    v-for="(style, status) in MEDDIC_STATUS_STYLE"
                    :key="status"
                    class="flex items-center mb-2 last:mb-0"
                  >
                    <div
                      class="min-w-3 min-h-3 rounded-full mr-2"
                      :style="{
                        backgroundColor: style.bg,
                        border:
                          status == MEDDIC_STATUS.NOT_FILLED
                            ? '1px solid #DCDCDC'
                            : 'none',
                      }"
                    ></div>
                    <span>{{ style.label }} </span>
                  </div>

                  <p class="text-wrap text-[#8C8C8C] text-xs mt-4 leading-5">
                    MEDDIC内容为AI自动生成，仅供参考。您可手动编辑修改AI生成的内容，也可对每个输入框锁定
                    / 解锁，锁定后AI生成的内容将不会覆盖文本框，解锁后AI会继续生成
                  </p>
                </div>
              </template>

              <img src="@/assets/customer/meddic-tip.svg" />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="owner" label="负责人" width="100">
        <template #default="{ row }">
          <div class="owner-name">{{ row.hostName }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="collaborator" label="协同跟进人" width="120">
        <template #default="{ row }">
          <div class="collaborator-name">
            {{ row.followNames || "-" }}
          </div>
        </template>
      </el-table-column>

      <el-table-column v-if="!isTeam" label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button
              :disabled="!enableCreateCommunicate(row)"
              type="primary"
              link
              size="small"
              @click="handleCommunicate(row)"
            >
              安排沟通
            </el-button>
            <el-button type="primary" link size="small" @click="handleDetail(row)">
              详情
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container" v-if="pagination.total > 10">
      <el-pagination
        v-model:current-page="pagination.pageNumber"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { computed } from "vue";
import MeddicIndicator from "./components/MeddicIndicator.vue";
import EventBus from "@/EventBus";
import iframeMessenger from "@/utils/iframeMessenger";
import {
  MEDDIC_STATUS,
  MEDDIC_STATUS_STYLE,
} from "@/views/customerAndBusiness/components/meddic/meddicConstants.js";
import { useCommonStore, useCustomerStore } from "@/store";

const maxWidth = 232;
const customerStore = useCustomerStore();

const isTeam = computed(() => {
  return customerStore.myTeam;
});

// Props定义
const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
  pagination: {
    type: Object,
    default: () => ({
      pageNumber: 1,
      pageSize: 10,
      total: 0,
    }),
  },
});

// Emits定义
const emit = defineEmits(["page-change", "refresh"]);

// 向外部发送事件的通用方法
const sendEventToParent = (eventType, data) => {
  // 向父窗口发送消息（如果在iframe中）
  iframeMessenger.sendToParent(eventType, data);

  // 同时触发内部EventBus事件
  EventBus.emit(eventType, data);
};

// 分页事件处理
const handleSizeChange = (size) => {
  emit("page-change", 1, size);
};

const handleCurrentChange = (page) => {
  emit("page-change", page);
};

// 事件处理
const handleCommunicate = (row) => {
  const eventData = {
    opportunityId: row.id || row.opportunityId,
    opportunityName: row.name || row.opportunityName,
  };
  sendEventToParent("create-opportunity-communicate", eventData);
};

function getStatusInfo(status) {
  let statusInfo = {
    1: {
      name: "进行中",
      color: "#436BFF",
      bgColor: "#F0F6FF",
    },
    2: {
      name: "赢单",
      color: "#04CCA4",
      bgColor: "#04CCA4",
    },
    3: {
      name: "输单",
      color: "#FA8C16",
      bgColor: "#FA8C16",
    },
  };
  let otherInfo = {
    name: "其他",
    color: "#595959",
    bgColor: "#F5F5F5",
  };
  return statusInfo[status] || otherInfo;
}

const commonStore = useCommonStore();
// 是否允许创建拜访
const enableCreateCommunicate = (item) => {
  const { ssoUserId, followSsoUserIds, status } = item;
  const { userInfo } = commonStore;
  return (
    (ssoUserId === userInfo.ssoUserId || followSsoUserIds.includes(userInfo.ssoUserId)) &&
    status === 1
  );
};

const handleDetail = (row) => {
  const eventData = {
    opportunityId: row.id || row.opportunityId,
    opportunityName: row.name || row.opportunityName,
    enableCreateCommunicate: enableCreateCommunicate(row),
  };
  sendEventToParent("open-opportunity-detail", eventData);
};
</script>

<style scoped>
.opportunity-list {
  width: 100%;
  background: white;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.opportunity-name {
  color: #303133;
  font-size: 14px;
  line-height: 1.4;
  padding: 8px 0;
}

.owner-name,
.collaborator-name {
  color: #606266;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid #f0f2f5;
  margin-top: 16px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

:deep(.el-table) {
  border: none;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa !important;
  border-bottom: 1px solid #e4e7ed;
  color: #606266;
  font-weight: 500;
  height: 48px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  padding: 16px 0;
  height: 60px;
}

:deep(.el-table tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-button--primary.is-link) {
  color: #436bff;
  font-size: 14px;
  padding: 0;
}

:deep(.el-button--primary.is-link:hover) {
  color: #436bff;
}

:deep(.el-button--primary.is-link:disabled) {
  color: rgb(166, 182, 240);
}

:deep(.el-table__header-wrapper) {
  border-top: 1px solid #e4e7ed;
}

:deep(.el-table__body-wrapper) {
  border-bottom: 1px solid #e4e7ed;
}

:deep.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}

:deep(.el-pagination) {
  --el-pagination-font-size: 14px;
}

div {
  --el-pagination-hover-color: #436bff;
}
</style>
